const express = require('express');
router = express.Router();
mySql = require('../db/index');
let send = (res, code, message) => {
    // res为200的时候初始化数据
    res.status(200).json({
        code,
        message
    })
}

//注册接口
router.post('/reg', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    let findUserSq = `SELECT * FROM user WHERE name = '${username}'`;
    mySql.getMysql(findUserSq).then((data) => {
        // 如果data不为空证明用户存在
        if (data[0] == undefined) {
            let saveUserSq = `INSERT INTO user(name,password) VALUES ('${username}','${password}')`
            mySql.getMysql(saveUserSq).then(function (data) {
                send(res, 0, '保存成功')
            }).catch(function (err) {
                send(res, 1, err.code)
            })
        } else {
            send(res, 1, '用户名重复')
        }
    }).catch((err) => {
        send(res, 1, err.code)
    })
})

//登录接口
router.post('/log', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    let findUserSq = `SELECT * FROM user WHERE name = '${username}'`;
    mySql.getMysql(findUserSq).then((data) => {
        // 如果data不为空证明用户存在
        if (data[0] == undefined) {
            send(res, 1, '用户名不存在')
        } else {
            if (data[0].password == password){
                res.cookie('username',data[0].name)
                send(res, 0, '恭喜您登陆成功。。。')
            } else{
                send(res, 2, '密码错误。。。')
            } 
        }
    }).catch((err) => {
        send(res, 1, err.code)
    })
})

//退出
router.get("/logout",function(req, res) {
 delete req.session.user;
 res.end();
})
 
//获取session
router.get("/session",function(req, res) {
 res.json({user:req.session.user});
 res.end();
})

module.exports = router